package current;

import java.util.concurrent.TimeUnit;

/**
 * Monitor的等待唤醒
 */
public class WaitAwait {

    public static void main(String[] args) throws InterruptedException {
        Object obj = new Object();
        Thread t1 = new Thread(() -> {
            System.out.println("before-wait-1...");
            // 获取对象monitor锁得到属主进入临界区才能进行等待
            synchronized (obj) {
                try {
                    obj.wait();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            System.out.println("after-wait-1...");
        });

        Thread t2 = new Thread(() -> {
            System.out.println("before-wait-2...");
            // 获取对象monitor锁得到属主进入临界区才能进行等待
            synchronized (obj) {
                try {
                    obj.wait();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            System.out.println("after-wait-2...");
        });

        t1.start();
        t2.start();

        // 非主线程先获取obj锁，让其可以执行到after-wait
        TimeUnit.MICROSECONDS.sleep(10);

        //信号唤醒，也需要先拿到锁，进入临界区
        synchronized (obj) {
            // 不需要写多个notify，直接notifyAll
            obj.notifyAll();
        }
    }
}
